<template>
  <div class="form">
    <div v-if="!uploadImg" class="navbar">
      <van-nav-bar
        :title="注册"
        left-arrow
        @click-left="onClickLeft"
        @click-right="onClickRight"
      />
    </div>
    <div v-if="uploadImg" class="upload-img">
      <div class="choose-img">
        <div class="img" v-for="(item, index) in imageData" :key="index">
          <img
            class="active"
            :src="item.value"
            alt=""
            @click="replace(item, index)"
          />
        </div>
      </div>
      <van-button
        class="button"
        round
        block
        type="primary"
        native-type="submit"
        color="#eb1f69"
        @click="uploadChange"
      >
        确定
      </van-button>
    </div>
    <div v-if="!uploadImg">
      <div class="headertitle">
        <img
          src="../assets/image/avator/add.jpg"
          alt=""
          v-if="!img"
          @click="imageChange"
        />
        <img :src="img" alt="" v-if="img" />
      </div>
    </div>
    <van-form @submit="onSubmit" v-if="!uploadImg">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />

        <van-field
          v-model="phone"
          name="phone"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { validator: asyncValidator, message: '请输入正确的手机号' },
          ]"
        />
        <van-field
          v-model="result"
          name="birthday"
          label="生日"
          placeholder="点击选择时间"
          @click="showPicker = true"
        />
        <van-popup v-model:show="showPicker" position="bottom">
          <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="confirm()"
            @cancel="cancel()"
          />
        </van-popup>
        <van-field name="gender" label="性别">
          <template #input>
            <van-radio-group v-model="checked" direction="horizontal">
              <van-radio checked-color="#eb1f69" name="1">男</van-radio>
              <van-radio checked-color="#eb1f69" name="0">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </van-cell-group>

      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          color="#eb1f69"
        >
          注册
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs } from "@vue/reactivity";
import { Toast } from "vant";
import router from "../router";
import axios from "../utils/axios";
export default {
  setup() {
    const state = reactive({
      imageData: [
        {
          key: 1,
          value: require("../assets/image/avator/1.png"),
        },
        {
          key: 2,
          value: require("../assets/image/avator/2.png"),
        },
        {
          key: 3,
          value: require("../assets/image/avator/3.png"),
        },
        {
          key: 4,
          value: require("../assets/image/avator/4.png"),
        },
        {
          key: 5,
          value: require("../assets/image/avator/5.png"),
        },
        {
          key: 6,
          value: require("../assets/image/avator/6.png"),
        },
        {
          key: 7,
          value: require("../assets/image/avator/7.png"),
        },
        {
          key: 8,
          value: require("../assets/image/avator/8.png"),
        },
        {
          key: 9,
          value: require("../assets/image/avator/9.png"),
        },
        {
          key: 10,
          value: require("../assets/image/avator/10.png"),
        },
        {
          key: 11,
          value: require("../assets/image/avator/11.png"),
        },
        {
          key: 12,
          value: require("../assets/image/avator/12.png"),
        },
      ],
      img: "",
      activeimg: 0,
      uploadImg: false,
      username: "",
      password: "",
      phone: "",
      result: "",
      checked: 1,
      showPicker: false,
      currentDate: new Date(),
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
    });
    const onClickLeft = () => history.back();

    const replace = (item) => {
      // console.log(item);
      state.img = item.value;
    };
    const imageChange = () => {
      state.uploadImg = true;
    };
    const uploadChange = () => {
      if (state.img) {
        state.uploadImg = false;
      } else {
        Toast.fail("请选择头像");
      }
    };
    //异步校验手机号
    const asyncValidator = (val) => {
      return new Promise((resolve) => {
        Toast.loading("验证中...");
        setTimeout(() => {
          var reg =
            /^((1[0-9][0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\d{8}$/;
          Toast.clear();
          resolve(reg.test(val));
        }, 300);
      });
    };

    //时间piker确认
    const confirm = () => {
      state.result = timeFormat(state.currentDate);
      state.showPicker = false;
    };
    //时间piker取消
    const cancel = () => {
      state.showPicker = false;
    };

    // 时间格式化 2019-09-08
    const timeFormat = (time) => {
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
      return year + "-" + month + "-" + day;
    };

    //提交表单
    const onSubmit = (values) => {
      // console.log(values);
      const arr = state.img.split(".");
      // console.log(arr);
      values.avator = `${arr[0].split("/")[2]}.${arr[2]}`;
      console.log(values);
      axios
        .post("/register", values)
        .then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            Toast.success("注册成功");
            setTimeout(() => {
              router.push("/login");
            }, 2000);
          } else {
            Toast.fail("注册失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    };
    return {
      ...toRefs(state),
      onClickLeft,
      imageChange,
      replace,
      uploadChange,
      confirm,
      timeFormat,
      cancel,
      onSubmit,
      asyncValidator,
    };
  },
};
</script>

<style lang="less" scoped>
.form {
  .upload-img {
    margin: 0 20px;
    .choose-img {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      margin: 40px 0;

      .img {
        margin: 10px;
        width: 80px;
        height: 80px;
        img {
          border-radius: 50%;
          width: 80px;
          height: 80px;
        }
      }
    }
  }

  .headertitle {
    text-align: center;
    img {
      border: 1px solid #755757;
      border-radius: 50%;
      width: 100px;
      height: 100px;
    }
  }
}
</style>